﻿using ExamPlat.Models;
using ExamPlat.Repositories;
using System;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace ExamPlat.Controllers
{
    public class LoginController : Controller
    {
        private static IUserInfoRepository userInfoRepository = new UserInfoRepository();
        // GET: Login
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(string loginAccount, string loginPwd)
        {
            loginAccount = loginAccount.Trim();
            loginPwd = loginPwd.Trim();
            if (string.IsNullOrWhiteSpace(loginAccount) || string.IsNullOrWhiteSpace(loginPwd))
            {
                ViewBag.Msg = "帐号或密码不能为空";
                return View();
            }
            UserInfo userInfo = userInfoRepository.GetUserInfoByAccountAndPwd(loginAccount, loginPwd);
            if (userInfo == null)
            {
                ViewBag.LoginAccount = loginAccount;
                ViewBag.Msg = "帐号或密码错误";
                return View();
            }
            else
            {
                HttpCookie curUser = new HttpCookie("CurUser");
                curUser["RoleID"] = userInfo.RoleID.ToString();
                curUser["LoginAccount"] = HttpUtility.UrlEncode(userInfo.LoginAccount, Encoding.Default);
                curUser["LoginPwd"] = HttpUtility.UrlEncode(userInfo.LoginPwd, Encoding.Default);
                curUser["UserName"] = HttpUtility.UrlEncode(userInfo.UserName, Encoding.Default);
                curUser.Expires = DateTime.Now.AddHours(1);
                Response.Cookies.Add(curUser);
                if (userInfo.RoleID == 1)
                {
                    return RedirectToAction("Index", "Admin");
                }
                else
                {
                    return View();
                }
            }
        }
    }
}